<template>
    <div class="p-2">
        <searchrevealing>
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="104px">
                <el-form-item label="商品名称" prop="styleName">
                    <el-input v-model="queryParams.styleName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="类目" prop="categoryIdList">
                    <el-cascader v-model="queryParams.categoryIdList" :options="options" style="width: 220px" clearable
                        collapse-tags filterable @change="handleChange" placeholder="请选择" :props="props" />
                </el-form-item>
                <el-form-item label="商品编码/69码" prop="styleCode">
                    <el-input v-model="queryParams.styleCode" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="供应商" prop="supplierName">
                    <el-input v-model="queryParams.supplierName" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" />
                </el-form-item>
                <el-form-item label="选品部门" prop="coreId">
                    <el-select v-model="queryParams.coreId" placeholder="请选择" clearable style="width: 220px" filterable>
                        <el-option v-for="dict in ReasonstorageList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门类型" prop="recruiterDeptId">
                    <el-select v-model="queryParams.recruiterDeptId" placeholder="请选择部门类型" clearable filterable
                        @change="departmentTypeChange" style="width: 220px">
                        <el-option v-for="dict in departmentTypeList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="部门名称" prop="recruiterDeptIds">
                    <el-select v-model="queryParams.recruiterDeptIds" placeholder="请选择部门名称" clearable filterable
                        @change="deptChange" style="width: 220px">
                        <el-option v-for="dict in deptList" :key="dict.deptId" :label="dict.deptName"
                            :value="dict.deptId" />
                    </el-select>
                </el-form-item>
                <el-form-item label="人员名称" prop="recruiterId">
                    <el-select v-model="queryParams.recruiterId" placeholder="请选择人员名称" clearable filterable
                        style="width: 220px">
                        <el-option v-for="dict in recruiterList" :key="dict.userId" :label="dict.nickName"
                            :value="dict.userId" />
                    </el-select>
                </el-form-item>

                <el-form-item label="价格" prop="price">
                    <el-input v-model="queryParams.price" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" oninput="value=value.replace(/[^0-9.]/g,'')" />
                </el-form-item>
                <el-form-item label="佣金" prop="commission">
                    <el-input v-model="queryParams.commission" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" oninput="value=value.replace(/[^0-9.]/g,'')">
                        <template #append>%</template>
                    </el-input>
                </el-form-item>
                <el-form-item label="成本价" prop="costPrice">
                    <el-input v-model="queryParams.costPrice" placeholder="请输入" clearable style="width: 220px"
                        @keyup.enter="handleQuery" oninput="value=value.replace(/[^0-9.]/g,'')" />
                </el-form-item>
                <el-form-item label="审核状态" prop="stockStatus">
                    <el-select v-model="queryParams.stockStatus" placeholder="请选择审核状态" clearable filterable
                        style="width: 220px">
                        <el-option v-for="dict in stockStatusList" :key="dict.value" :label="dict.label"
                            :value="dict.value" />
                    </el-select>
                </el-form-item>
            </el-form>
            <div class="form_button">
                <el-button type="primary" @click="handleQuery" :loading="queryLoading">查询</el-button>
                <el-button @click="resetQuery" :loading="queryLoading">重置</el-button>
            </div>
        </searchrevealing>
        <el-card shadow="never">
            <template #header>
                <el-row :gutter="10" class="mb8">

                    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :name="'产品部入库审核'"
                        @updateColumn="getColmun"></right-toolbar>
                </el-row>
            </template>
            <el-table v-loading="loading" :data="selectionRecordList" border @header-dragend="dragEnd">
                <el-table-column label="序号" type="index" width="55" align="center" :fixed="true" />
                <el-table-column v-for="(item, index) in inventoryReviewColumns" :key="index" :label="item.label"
                    align="center" :prop="item.prop" show-overflow-tooltip :fixed="item.fixed" :width="item.width">
                    <template #default="scope">
                        <image-preview v-if="item.prop == 'productImage'" :src="scope.row.productImage" :width="50"
                            :height="50" />
                        <span v-if="item.prop == 'warehouse'">{{ scope.row.warehouse ? '是' : '否' }}</span>
                        <div v-if="item.prop == 'hmMechanismsList'">
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[0] ||
                                null,
                                '一') }}</div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[1] ||
                                null,
                                '二') }}</div>
                            <div>{{ computedMechanism(scope.row.hmMechanismsList && scope.row.hmMechanismsList[2] ||
                                null,
                                '三') }}</div>
                        </div>
                        <span v-if="item.prop == 'stockStatus'">
                            <div>{{ scope.row.stockStatus == '0' ? '待审核' : scope.row.stockStatus == '1' ? '已驳回' : '已通过'
                                }}
                            </div>
                        </span>
                        <!-- 部门类型 -->
                        <span v-if="item.prop == 'type'">{{ scope.row.type == 1 ? '研发部' : '招商部' }}</span>
                    </template>
                </el-table-column>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
                    <template #default="scope">
                        <el-button link type="primary" @click="handleInfo(scope.row)" class="color_theme"
                            v-if="scope.row.stockStatus == '0'">入库</el-button>
                        <el-button link type="primary" @click="getDetail(scope.row)" class="color_theme"
                            v-if="scope.row.stockStatus !== '0'">详情</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize" @pagination="paginationChange" />
        </el-card>

        <!-- 商品入库信息核对  -->
        <goodswarehousing @doClose="goodswarehousingClose" :goodswarehousingVisible="goodswarehousingVisible"
            :goodswarehousingData="goodswarehousingData"></goodswarehousing>
        <!-- 商品入库信息详情  -->
        <inventoryReviewDetail @doClose="inventoryReviewDetailClose"
            :goodswarehousingVisible="inventoryReviewDetailCloseVisible"
            :goodswarehousingData="inventoryReviewDetailData">
        </inventoryReviewDetail>
    </div>
</template>



<script setup name="InventoryReview" lang="ts">
const { proxy } = getCurrentInstance() as any;
import goodswarehousing from './components/goodswarehousing.vue';
import inventoryReviewDetail from './components/inventoryReviewDetail.vue'
import { QualityControlForm } from '@/api/group/qualityControl/types';
import { InventoryReviewQueryParmas, InventoryReviewVO } from '@/api/group/productOutbound/types'
import { getUserList, loginDeptList } from '@/api/group/qualityControl'
import { getSystemList } from '@/api/group/qualityControl'
import { getStockPcList, getCoreIdList, getCategoryLists } from '@/api/group/productOutbound/index'
import { queryOperationDeptList } from '@/api/group/productSelectionPricing'
const inventoryReviewColumns = ref()
const props = {
    multiple: true
}
const columnData = ref()
const selectionRecordList = ref<InventoryReviewVO[]>([]);
const loading = ref(true);
const total = ref(0);
const showSearch = ref(true);
const queryFormRef = ref<ElFormInstance>();
const deptList = ref<{ deptId: string; deptName: string; }[]>([])
const recruiterList = ref<{ userId: string; nickName: string; }[]>([])
const goodswarehousingVisible = ref(false)
const inventoryReviewDetailCloseVisible = ref(false)
const goodswarehousingData = ref<QualityControlForm>({})
const inventoryReviewDetailData = ref<QualityControlForm>({})

const ReasonstorageList = ref<{ deptName: string; deptId: string }[]>([]);

const queryLoading = ref(false)

const queryParams = ref<InventoryReviewQueryParmas>({
    pageNum: 1,
    pageSize: 10,
    styleName: undefined,
    styleCode: undefined,
    supplierName: undefined,
    coreId: undefined,
    recruiterDeptId: undefined,
    recruiterDeptIds: undefined,
    recruiterId: undefined,
    price: undefined,
    commission: undefined,
    costPrice: undefined,
    type: undefined,
    stockStatus: undefined,
    categoryIdList: []
})

// 部门类型
const departmentTypeList = ref()

// 审核状态
const stockStatusList = ref([
    { label: '待审核', value: '0' },
    { label: '已驳回', value: '1' },
    { label: '已通过', value: '2' },
])

const options = ref()


/**
 * 直播机制
 */
const computedMechanism = (row: any, numbers: string) => {
    if (row) {
        const price = row.price ? row.price : '-'
        const commission = row.commission ? row.commission + '%' : '-'
        const brokerage = row.brokerage ? row.brokerage + '%' : '-'
        const liveStreamingMechanism = row.liveStreamingMechanism ? row.liveStreamingMechanism : '-'
        const costPrice = row.costPrice ? row.costPrice : '-'
        if (row.cooperationMode) {
            if (row.cooperationMode == '分佣') {
                return '机制' + numbers + ': ' + '售价:' + price + ' 佣金:' + commission + ' 补充佣金:' + brokerage + ' 机制:' + liveStreamingMechanism + ' 成本:' + costPrice
            } else {
                return '机制' + numbers + ': ' + '成本:' + costPrice + ' 机制:' + liveStreamingMechanism
            }
        }
    }

}

/** 获取类目 */
const getCategoryList = async () => {
    try {
        const res = await getCategoryLists();
        const processedData = renameField(res.data);
        options.value = processedData;
    } catch (error) {
        console.error('Failed to get category list:', error);
        options.value = [];
    }
}
const renameField = (arr: any[]) => {
    return arr.filter(item => item.categoryStatus === 0).map(element => {
        if (element.children) {
            element.children = renameField(element.children);
        }
        return {
            label: element.categoryName,
            value: element.categoryId,
            ...element,
        };
    });
}

/**
 * 获取选品部门
 */
const getAnorch = async () => {
    const res = await queryOperationDeptList()
    ReasonstorageList.value = res.data
}

/**
 * 获取招商部门信息
 */
const getDeptLists = async () => {
    const res = await loginDeptList()
    deptList.value = res.data
}
/** 
 * 获取部门类型
 */
const getdeptType = async () => {
    const res = await getSystemList({ parentId: '1861962988832542721' })
    departmentTypeList.value = res.data
}
/**
 * 部门筛选
 */
const departmentTypeChange = async (parentId: string) => {
    if (parentId) {
        queryParams.value.recruiterDeptIds = undefined
        queryParams.value.recruiterId = undefined
        const res = await getSystemList({ parentId })
        deptList.value = res.data
        recruiterList.value = []
    } else {
        deptList.value = []
        recruiterList.value = []
        queryParams.value.recruiterDeptIds = undefined
        queryParams.value.recruiterId = undefined
    }
}

/**
 *  根据招商部获取招商员
 */
const deptChange = async (event: string) => {
    if (event) {
        const res = await getUserList({ deptId: event })
        recruiterList.value = res.rows
        queryParams.value.recruiterId = undefined
    } else {
        recruiterList.value = []
        queryParams.value.recruiterId = undefined
    }
}



// 筛选类目change事件
const handleChange = (val: [string, string, string]) => {

}
/** 根据合同类型获取合同名称 */
const contractNameByType = async (type: string, row: any) => {
    if (row) {
        const rows = row.filter((item: any) =>
            item.contractType == type
        )
        if (rows.length > 0) {
            if (type == '供销合同') {
                goodswarehousingData.value.contractSellOssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
                inventoryReviewDetailData.value.contractSellOssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
            } else if (type == '破价合同') {
                goodswarehousingData.value.contractDiscountOssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
                inventoryReviewDetailData.value.contractDiscountOssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
            } else if (type == '保证金协议') {
                goodswarehousingData.value.marginNameUrlssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
                inventoryReviewDetailData.value.marginNameUrlssId = import.meta.env.VITE_APP_PIC_URL + rows[0].contractFile
            }
            return rows[0].fileName
        } else {
            return '-'
        }
    } else {
        return '-'
    }
}
/** 入库 */
const handleInfo = async (row?: InventoryReviewVO) => {
    const res: any = await getStockPcList({ id: (row as any).id });
    goodswarehousingData.value = res.rows[0]
    goodswarehousingData.value.contractSellName = await contractNameByType('供销合同', goodswarehousingData.value.contractList)
    goodswarehousingData.value.contractDiscountName = await contractNameByType('破价合同', goodswarehousingData.value.contractList)
    goodswarehousingData.value.marginName = await contractNameByType('保证金协议', goodswarehousingData.value.contractList)

    goodswarehousingVisible.value = true
};
/** 详情 */
const getDetail = async (row?: InventoryReviewVO) => {
    const res: any = await getStockPcList({ id: (row as any).id });
    inventoryReviewDetailData.value = res.rows[0]
    inventoryReviewDetailData.value.contractSellName = await contractNameByType('供销合同', inventoryReviewDetailData.value.contractList)
    inventoryReviewDetailData.value.contractDiscountName = await contractNameByType('破价合同', inventoryReviewDetailData.value.contractList)
    inventoryReviewDetailData.value.marginName = await contractNameByType('保证金协议', inventoryReviewDetailData.value.contractList)

    inventoryReviewDetailCloseVisible.value = true
}

/** 查询列表 */
const getList = async () => {
    try {
        loading.value = true;
        const res = await getStockPcList({ ...queryParams.value, recruiterDeptId: queryParams.value.recruiterDeptIds || queryParams.value.recruiterDeptId });
        (selectionRecordList.value as any) = res.rows;
        total.value = res.total;
        loading.value = false;
        queryLoading.value = false
    } catch (e) {
    } finally {
        loading.value = false;
    }
};
/** 搜索按钮操作 */
const handleQuery = () => {
    queryLoading.value = true
    queryParams.value.pageNum = 1;
    getList();
};
/** 重置按钮操作 */
const resetQuery = () => {
    queryFormRef.value?.resetFields();
    recruiterList.value = []
    deptList.value = []
    handleQuery();
};
/** 商品入库关闭 */
const goodswarehousingClose = () => {
    goodswarehousingVisible.value = false
    getList();
}
/** 商品详情关闭 */
const inventoryReviewDetailClose = () => {
    inventoryReviewDetailCloseVisible.value = false
    getList();
}
/** 获取colmun */
const getColmun = async () => {
    const columnDatas = await proxy?.useColumn('产品部入库审核')
    inventoryReviewColumns.value = columnDatas.columnCustom
    columnData.value = columnDatas
    queryParams.value.pageSize = columnDatas.columnPageSize || 10
}
/** 拖拽事件 */
const dragEnd = async (newWidth: number, oldWidth: number, column: any, event: MouseEvent) => {
    columnData.value.columnCustom.map((item: any) => {
        if (item.prop == column.property) {
            item.width = newWidth
        }
    })
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
}
/** 页数变化 */
const paginationChange = async () => {
    await getList();
    await proxy?.useColumnUpdate(columnData.value, queryParams.value.pageSize)
    getColmun()
}
onMounted(async () => {
    queryParams.value.pageNum = 1;
    await getColmun();
    await getList();
    getdeptType()
    getAnorch();
    getCategoryList();
})

</script>
<style lang="scss" scoped>
.mb96 {
    margin-bottom: 96px;
}

.form_button {
    display: flex;
    justify-content: flex-end;
}
</style>